<template>
  <div class="realtime-dashboard">
    <!-- 大屏头部 -->
    <div class="dashboard-header">
      <div class="header-left">
        <h1 class="dashboard-title">📊 库存统计实时大屏</h1>
        <div class="subtitle">数据实时更新 · 智能分析 · 可视化展示</div>
      </div>
      <div class="header-right">
        <div class="connection-status" :class="{ connected: isSignalRConnected }">
          <div class="status-dot"></div>
          <span>{{ isSignalRConnected ? '实时连接' : '连接断开' }}</span>
        </div>
        <div class="activity-status" :class="{ high: dataActivity.isHighActivity }">
          <div class="activity-indicator">
            <span class="activity-icon">{{ dataActivity.isHighActivity ? '🔥' : '📊' }}</span>
            <span class="activity-text">
              {{ dataActivity.isHighActivity ? '高活跃' : '正常' }}
            </span>
          </div>
          <div class="activity-details">
            <span class="activity-count">{{ dataActivity.changeHistory.length }} 次变更</span>
            <span class="activity-time">{{ formatActivityTime(dataActivity.lastChangeTime) }}</span>
          </div>
        </div>
        <div class="update-time">
          <span>最后更新: {{ formatTime(lastUpdateTime) }}</span>
          <div class="auto-refresh-indicator">
            <span class="auto-icon">⚡</span>
            <span>自动刷新已启用</span>
          </div>
          <div class="global-push-indicator" :class="{ active: isGlobalPushing }">
            <span class="push-icon" :class="{ spinning: isGlobalPushing }">🌍</span>
            <span>{{ isGlobalPushing ? '全量推送中...' : '全量推送' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速统计卡片区域 -->
    <div class="stats-overview">
      <div class="stat-card primary" :class="{ pulse: cardAnimations.products }">
        <div class="card-icon">📦</div>
        <div class="card-content">
          <div class="card-value">{{ dashboardData?.inventoryQuantityRatio?.count || 0 }}</div>
          <div class="card-label">商品种类</div>
          <div class="card-change">+{{ todayChanges.products }}</div>
        </div>
        <div class="card-chart">
          <div class="mini-chart" :style="{ width: `${Math.min(100, (dashboardData?.inventoryQuantityRatio?.count || 0) / 10)}%` }"></div>
        </div>
      </div>

      <div class="stat-card success" :class="{ pulse: cardAnimations.value }">
        <div class="card-icon">💰</div>
        <div class="card-content">
          <div class="card-value">¥{{ formatAmount(dashboardData?.inventoryAmountRatio?.totalAmount) }}</div>
          <div class="card-label">总库存价值</div>
          <div class="card-change">+¥{{ formatAmount(todayChanges.value) }}</div>
        </div>
        <div class="card-chart">
          <div class="mini-chart" :style="{ width: '85%' }"></div>
        </div>
      </div>

      <div class="stat-card info" :class="{ pulse: cardAnimations.inbound }">
        <div class="card-icon">📈</div>
        <div class="card-content">
          <div class="card-value">{{ dashboardData?.recentStatistics?.totalInboundQuantity || 0 }}</div>
          <div class="card-label">近30天入库</div>
          <div class="card-change">+{{ todayChanges.inbound }}</div>
        </div>
        <div class="card-chart">
          <div class="mini-chart" :style="{ width: '72%' }"></div>
        </div>
      </div>

      <div class="stat-card warning" :class="{ pulse: cardAnimations.outbound }">
        <div class="card-icon">📉</div>
        <div class="card-content">
          <div class="card-value">{{ dashboardData?.recentStatistics?.totalOutboundQuantity || 0 }}</div>
          <div class="card-label">近30天出库</div>
          <div class="card-change">+{{ todayChanges.outbound }}</div>
        </div>
        <div class="card-chart">
          <div class="mini-chart" :style="{ width: '68%' }"></div>
        </div>
      </div>

      <div class="stat-card danger" :class="{ pulse: cardAnimations.alerts }" v-if="hasLowStockAlert">
        <div class="card-icon">⚠️</div>
        <div class="card-content">
          <div class="card-value">{{ dashboardData?.lowStockAlert?.totalAlertCount || 0 }}</div>
          <div class="card-label">库存预警</div>
          <div class="card-change">{{ getAlertChangeText() }}</div>
        </div>
        <div class="card-chart">
          <div class="mini-chart alert" :style="{ width: '95%' }"></div>
        </div>
      </div>
    </div>

    <!-- 主要图表区域 -->
    <div class="charts-main-area">
      <!-- 第一行：饼图区域 -->
      <div class="chart-row">
        <div class="chart-container">
          <div class="chart-header">
            <h3>📊 库存数量占比分析</h3>
            <div class="chart-controls">
              <select v-model="quantityTopCount" @change="refreshQuantityData">
                <option value="5">Top 5</option>
                <option value="10">Top 10</option>
                <option value="15">Top 15</option>
                <option value="20">Top 20</option>
              </select>
            </div>
          </div>
          <div class="chart-content">
            <v-chart 
              class="chart" 
              :option="quantityPieOption" 
              :autoresize="true"
              @click="onChartClick"
            />
          </div>
        </div>

        <div class="chart-container">
          <div class="chart-header">
            <h3>💰 库存金额占比分析</h3>
            <div class="chart-controls">
              <select v-model="amountTopCount" @change="refreshAmountData">
                <option value="5">Top 5</option>
                <option value="10">Top 10</option>
                <option value="15">Top 15</option>
                <option value="20">Top 20</option>
              </select>
            </div>
          </div>
          <div class="chart-content">
            <v-chart 
              class="chart" 
              :option="amountPieOption" 
              :autoresize="true"
              @click="onChartClick"
            />
          </div>
        </div>
      </div>

      <!-- 第二行：趋势分析 -->
      <div class="chart-row">
        <div class="chart-container full-width">
          <div class="chart-header">
            <h3>📈 出入库趋势分析</h3>
            <div class="chart-controls">
              <select v-model="statisticsPeriod" @change="refreshStatisticsData">
                <option value="7">近7天</option>
                <option value="15">近15天</option>
                <option value="30">近30天</option>
                <option value="60">近60天</option>
              </select>
            </div>
          </div>
          <div class="chart-content large">
            <v-chart 
              class="chart" 
              :option="statisticsLineOption" 
              :autoresize="true"
            />
          </div>
        </div>
      </div>

      <!-- 第三行：排名分析 -->
      <div class="chart-row">
        <div class="chart-container">
          <div class="chart-header">
            <h3>🏆 入库排名TOP10</h3>
            <div class="chart-info">
              <span class="info-badge pulse">实时更新</span>
              <div class="chart-toggle">
                <button 
                  @click="toggleInboundView" 
                  class="toggle-btn"
                  :class="{ active: inboundViewType === 'chart' }"
                >
                  📊 柱状图
                </button>
                <button 
                  @click="toggleInboundView" 
                  class="toggle-btn"
                  :class="{ active: inboundViewType === 'table' }"
                >
                  📋 表格
                </button>
              </div>
            </div>
          </div>
          <div class="chart-content">
            <!-- 柱状图视图 -->
            <v-chart 
              v-if="inboundViewType === 'chart'"
              class="chart" 
              :option="inboundRankingOption" 
              :autoresize="true"
            />
            <!-- 表格视图 -->
            <div v-else class="ranking-table">
              <div class="table-header">
                <div class="rank-col">排名</div>
                <div class="name-col">商品名称</div>
                <div class="quantity-col">入库数量</div>
                <div class="operations-col">操作次数</div>
              </div>
              <div class="table-body">
                <div 
                  v-for="(item, index) in dashboardData?.inboundRanking?.rankings?.slice(0, 10) || []" 
                  :key="item.goodsId"
                  class="table-row"
                  :class="{ 'top-three': index < 3, 'new-entry': isNewEntry('inbound', item.goodsId) }"
                >
                  <div class="rank-col">
                    <div class="rank-badge" :class="getRankClass(index + 1)">
                      {{ index + 1 }}
                    </div>
                  </div>
                  <div class="name-col">
                    <div class="goods-name">{{ item.goodsName }}</div>
                  </div>
                  <div class="quantity-col">
                    <div class="quantity-value">{{ item.totalQuantity.toLocaleString() }}</div>
                  </div>
                  <div class="operations-col">
                    <div class="operations-value">{{ item.operationCount }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="chart-container">
          <div class="chart-header">
            <h3>📤 出库排名TOP10</h3>
            <div class="chart-info">
              <span class="info-badge pulse">实时更新</span>
              <div class="chart-toggle">
                <button 
                  @click="toggleOutboundView" 
                  class="toggle-btn"
                  :class="{ active: outboundViewType === 'chart' }"
                >
                  📊 柱状图
                </button>
                <button 
                  @click="toggleOutboundView" 
                  class="toggle-btn"
                  :class="{ active: outboundViewType === 'table' }"
                >
                  📋 表格
                </button>
              </div>
            </div>
          </div>
          <div class="chart-content">
            <!-- 柱状图视图 -->
            <v-chart 
              v-if="outboundViewType === 'chart'"
              class="chart" 
              :option="outboundRankingOption" 
              :autoresize="true"
            />
            <!-- 表格视图 -->
            <div v-else class="ranking-table">
              <div class="table-header">
                <div class="rank-col">排名</div>
                <div class="name-col">商品名称</div>
                <div class="quantity-col">出库数量</div>
                <div class="operations-col">操作次数</div>
              </div>
              <div class="table-body">
                <div 
                  v-for="(item, index) in dashboardData?.outboundRanking?.rankings?.slice(0, 10) || []" 
                  :key="item.goodsId"
                  class="table-row"
                  :class="{ 'top-three': index < 3, 'new-entry': isNewEntry('outbound', item.goodsId) }"
                >
                  <div class="rank-col">
                    <div class="rank-badge" :class="getRankClass(index + 1)">
                      {{ index + 1 }}
                    </div>
                  </div>
                  <div class="name-col">
                    <div class="goods-name">{{ item.goodsName }}</div>
                  </div>
                  <div class="quantity-col">
                    <div class="quantity-value">{{ item.totalQuantity.toLocaleString() }}</div>
                  </div>
                  <div class="operations-col">
                    <div class="operations-value">{{ item.operationCount }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第四行：占比详细分析表格 -->
      <div class="chart-row">
        <div class="chart-container">
          <div class="chart-header">
            <h3>📊 库存数量占比详细分析</h3>
            <div class="chart-info">
              <span class="info-badge pulse">实时更新</span>
              <div class="update-indicator" :class="{ active: isQuantityUpdating }">
                <span class="update-dot"></span>
                数据更新中...
              </div>
            </div>
          </div>
          <div class="chart-content">
            <div class="analysis-table">
              <div class="table-header">
                <div class="name-col">商品名称</div>
                <div class="percentage-col">占比</div>
                <div class="trend-col">趋势</div>
                <div class="status-col">状态</div>
              </div>
              <div class="table-body">
                <div 
                  v-for="(item, index) in dashboardData?.inventoryQuantityRatio?.showGoods || []" 
                  :key="item.goodsId"
                  class="table-row"
                  :class="{ 'updated': isItemUpdated('quantity', item.goodsId) }"
                >
                  <div class="name-col">
                    <div class="goods-name">{{ item.goodsName }}</div>
                  </div>
                  <div class="percentage-col">
                    <div class="percentage-bar">
                      <div class="bar-bg">
                        <div 
                          class="bar-fill quantity" 
                          :style="{ width: `${item.percentage}%` }"
                        ></div>
                      </div>
                      <span class="percentage-text">{{ item.percentage.toFixed(1) }}%</span>
                    </div>
                  </div>
                  <div class="trend-col">
                    <div class="trend-indicator" :class="getTrendClass('quantity', item.goodsId)">
                      {{ getTrendIcon('quantity', item.goodsId) }}
                    </div>
                  </div>
                  <div class="status-col">
                    <span class="status-badge" :class="getStatusClass(item.percentage)">
                      {{ getStatusText(item.percentage) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="chart-container">
          <div class="chart-header">
            <h3>💰 库存金额占比详细分析</h3>
            <div class="chart-info">
              <span class="info-badge pulse">实时更新</span>
              <div class="update-indicator" :class="{ active: isAmountUpdating }">
                <span class="update-dot"></span>
                数据更新中...
              </div>
            </div>
          </div>
          <div class="chart-content">
            <div class="analysis-table">
              <div class="table-header">
                <div class="name-col">商品名称</div>
                <div class="amount-col">金额</div>
                <div class="percentage-col">占比</div>
                <div class="trend-col">趋势</div>
              </div>
              <div class="table-body">
                <div 
                  v-for="(item, index) in dashboardData?.inventoryAmountRatio?.goodsAmountRatios || []" 
                  :key="item.goodsId"
                  class="table-row"
                  :class="{ 'updated': isItemUpdated('amount', item.goodsId) }"
                >
                  <div class="name-col">
                    <div class="goods-name">{{ item.goodsName }}</div>
                  </div>
                  <div class="amount-col">
                    <div class="amount-value">¥{{ item.totalAmount.toLocaleString() }}</div>
                    <div class="amount-detail">{{ item.stockQuantity }} × ¥{{ item.unitPrice }}</div>
                  </div>
                  <div class="percentage-col">
                    <div class="percentage-bar">
                      <div class="bar-bg">
                        <div 
                          class="bar-fill amount" 
                          :style="{ width: `${item.amountPercentage}%` }"
                        ></div>
                      </div>
                      <span class="percentage-text">{{ item.amountPercentage.toFixed(1) }}%</span>
                    </div>
                  </div>
                  <div class="trend-col">
                    <div class="trend-indicator" :class="getTrendClass('amount', item.goodsId)">
                      {{ getTrendIcon('amount', item.goodsId) }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 实时消息和预警区域 -->
    <div class="bottom-section">
      <!-- 实时消息流 -->
      <div class="message-stream">
        <div class="section-header">
          <h3>🔔 实时消息流</h3>
          <button @click="clearMessages" class="clear-btn">清空</button>
        </div>
        <div class="message-list">
          <div 
            v-for="message in realtimeMessages" 
            :key="message.id"
            class="message-item"
            :class="message.type"
          >
            <div class="message-icon">{{ getMessageIcon(message.type) }}</div>
            <div class="message-content">
              <div class="message-title">{{ message.title }}</div>
              <div class="message-text">{{ message.content }}</div>
            </div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
          <div v-if="realtimeMessages.length === 0" class="no-messages">
            暂无实时消息
          </div>
        </div>
      </div>

      <!-- 库存预警面板 -->
      <div class="alerts-panel" v-if="hasLowStockAlert">
        <div class="section-header">
          <h3>⚠️ 库存预警</h3>
          <div class="alert-count">{{ dashboardData?.lowStockAlert?.totalAlertCount }} 项</div>
        </div>
        <div class="alerts-list">
          <div 
            v-for="alert in dashboardData?.lowStockAlert?.lowStockItems?.slice(0, 5) || []" 
            :key="alert.goodsId"
            class="alert-item"
            :class="getAlertClass(alert.alertLevel)"
          >
            <div class="alert-icon">{{ getAlertIcon(alert.alertLevel) }}</div>
            <div class="alert-info">
              <div class="alert-name">{{ alert.goodsName }}</div>
              <div class="alert-stock">库存: {{ alert.currentStock }}/{{ alert.minStockLevel }}</div>
              <div class="alert-description">{{ alert.alertDescription }}</div>
              <div class="alert-gap" v-if="alert.stockGap > 0">缺货: {{ alert.stockGap }} 件</div>
            </div>
            <div class="alert-meta">
              <div class="alert-level">{{ getAlertLevelText(alert.alertLevel) }}</div>
              <div class="alert-time">{{ formatAlertTime(alert.alertTime) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { distributedSignalRService } from '@/services/DistributedSignalRService'
import { signalRService } from '@/services/SignalRService' // 保持向后兼容
import { statisticsService } from '@/services/StatisticsService'
import type { DashboardData, SystemMessage } from '@/services/StatisticsService'

// 注册ECharts组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent
])

// 响应式数据
const isSignalRConnected = ref(false)
const useDistributedSignalR = ref(true) // 是否使用分布式SignalR服务
const lastUpdateTime = ref(new Date())
const dashboardData = ref<DashboardData | null>(null)
const isRefreshing = ref(false)
const isGlobalPushing = ref(false)

// 图表配置参数
const quantityTopCount = ref(10)
const amountTopCount = ref(10)
const statisticsPeriod = ref(30)

// 视图切换状态
const inboundViewType = ref<'chart' | 'table'>('chart')
const outboundViewType = ref<'chart' | 'table'>('chart')

// 更新状态指示器
const isQuantityUpdating = ref(false)
const isAmountUpdating = ref(false)

// 历史数据用于趋势分析
const previousQuantityData = ref<Map<number, number>>(new Map())
const previousAmountData = ref<Map<number, number>>(new Map())
const previousInboundRanking = ref<Map<number, number>>(new Map())
const previousOutboundRanking = ref<Map<number, number>>(new Map())

// 新条目标记
const newEntries = ref<Set<string>>(new Set())
const updatedItems = ref<Set<string>>(new Set())

// 卡片动画状态
const cardAnimations = reactive({
  products: false,
  value: false,
  inbound: false,
  outbound: false,
  alerts: false
})

// 今日变化数据（模拟）
const todayChanges = reactive({
  products: 0,
  value: 0,
  inbound: 0,
  outbound: 0
})

// 实时消息
interface RealtimeMessage {
  id: string
  type: 'success' | 'warning' | 'info' | 'error'
  title: string
  content: string
  timestamp: Date
}

const realtimeMessages = ref<RealtimeMessage[]>([])

// 计算属性
const hasLowStockAlert = computed(() => {
  return (dashboardData.value?.lowStockAlert?.totalAlertCount || 0) > 0 && 
         (dashboardData.value?.lowStockAlert?.lowStockItems?.length || 0) > 0
})

// ECharts配置选项
const quantityPieOption = computed(() => ({
  title: {
    text: '库存数量占比',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
    backgroundColor: 'rgba(0,0,0,0.8)',
    textStyle: { color: '#fff' }
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: 10,
    top: 20,
    bottom: 20,
    textStyle: { fontSize: 12 }
  },
  series: [
    {
      name: '库存数量',
      type: 'pie',
      radius: ['30%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      labelLine: {
        show: false
      },
      data: dashboardData.value?.inventoryQuantityRatio?.showGoods?.map(item => ({
        value: item.percentage,
        name: item.goodsName
      })) || [],
      animationType: 'scale',
      animationEasing: 'elasticOut'
    }
  ]
}))

const amountPieOption = computed(() => ({
  title: {
    text: '库存金额占比',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: ¥{c} ({d}%)',
    backgroundColor: 'rgba(0,0,0,0.8)',
    textStyle: { color: '#fff' }
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: 10,
    top: 20,
    bottom: 20,
    textStyle: { fontSize: 12 }
  },
  series: [
    {
      name: '库存金额',
      type: 'pie',
      radius: ['30%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      labelLine: {
        show: false
      },
      data: dashboardData.value?.inventoryAmountRatio?.goodsAmountRatios?.map(item => ({
        value: item.totalAmount,
        name: item.goodsName
      })) || [],
      animationType: 'scale',
      animationEasing: 'elasticOut'
    }
  ]
}))

const statisticsLineOption = computed(() => ({
  title: {
    text: '出入库趋势分析',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 18,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    },
    backgroundColor: 'rgba(0,0,0,0.8)',
    textStyle: { color: '#fff' }
  },
  toolbox: {
    feature: {
      dataView: { show: true, readOnly: false },
      magicType: { show: true, type: ['line', 'bar'] },
      restore: { show: true },
      saveAsImage: { show: true }
    },
    right: 20,
    top: 20
  },
  legend: {
    data: ['入库数量', '出库数量', '净变化'],
    top: 50,
    textStyle: { fontSize: 14 }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '10%',
    top: '20%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: dashboardData.value?.recentStatistics?.dailyStatistics?.map(item => 
        new Date(item.date).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
      ) || [],
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '数量',
      axisLabel: {
        formatter: '{value}'
      }
    }
  ],
  dataZoom: [
    {
      type: 'inside',
      start: 0,
      end: 100
    },
    {
      start: 0,
      end: 100,
      handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
      handleSize: '80%',
      handleStyle: {
        color: '#fff',
        shadowBlur: 3,
        shadowColor: 'rgba(0, 0, 0, 0.6)',
        shadowOffsetX: 2,
        shadowOffsetY: 2
      }
    }
  ],
  series: [
    {
      name: '入库数量',
      type: 'line',
      smooth: true,
      data: dashboardData.value?.recentStatistics?.dailyStatistics?.map(item => item.inboundQuantity) || [],
      itemStyle: {
        color: '#5cb87a'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(92, 184, 122, 0.3)'
          }, {
            offset: 1, color: 'rgba(92, 184, 122, 0.1)'
          }]
        }
      }
    },
    {
      name: '出库数量',
      type: 'line',
      smooth: true,
      data: dashboardData.value?.recentStatistics?.dailyStatistics?.map(item => item.outboundQuantity) || [],
      itemStyle: {
        color: '#e55656'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(229, 86, 86, 0.3)'
          }, {
            offset: 1, color: 'rgba(229, 86, 86, 0.1)'
          }]
        }
      }
    },
    {
      name: '净变化',
      type: 'line',
      smooth: true,
      data: dashboardData.value?.recentStatistics?.dailyStatistics?.map(item => item.netChange) || [],
      itemStyle: {
        color: '#3fb1e3'
      },
      lineStyle: {
        width: 3,
        type: 'dashed'
      }
    }
  ]
}))

const inboundRankingOption = computed(() => ({
  title: {
    text: '入库排名',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    backgroundColor: 'rgba(0,0,0,0.8)',
    textStyle: { color: '#fff' }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01],
    axisLabel: {
      formatter: '{value}'
    }
  },
  yAxis: {
    type: 'category',
    data: dashboardData.value?.inboundRanking?.rankings?.slice(0, 10).map(item => 
      item.goodsName.length > 8 ? item.goodsName.substring(0, 8) + '...' : item.goodsName
    ) || [],
    axisLabel: {
      fontSize: 12
    }
  },
  series: [
    {
      name: '入库数量',
      type: 'bar',
      data: dashboardData.value?.inboundRanking?.rankings?.slice(0, 10).map(item => item.totalQuantity) || [],
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 1,
          y2: 0,
          colorStops: [{
            offset: 0, color: '#5cb87a'
          }, {
            offset: 1, color: '#7ed69a'
          }]
        },
        borderRadius: [0, 4, 4, 0]
      },
      label: {
        show: true,
        position: 'right',
        formatter: '{c}',
        fontSize: 12
      }
    }
  ]
}))

const outboundRankingOption = computed(() => ({
  title: {
    text: '出库排名',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    backgroundColor: 'rgba(0,0,0,0.8)',
    textStyle: { color: '#fff' }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01],
    axisLabel: {
      formatter: '{value}'
    }
  },
  yAxis: {
    type: 'category',
    data: dashboardData.value?.outboundRanking?.rankings?.slice(0, 10).map(item => 
      item.goodsName.length > 8 ? item.goodsName.substring(0, 8) + '...' : item.goodsName
    ) || [],
    axisLabel: {
      fontSize: 12
    }
  },
  series: [
    {
      name: '出库数量',
      type: 'bar',
      data: dashboardData.value?.outboundRanking?.rankings?.slice(0, 10).map(item => item.totalQuantity) || [],
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 1,
          y2: 0,
          colorStops: [{
            offset: 0, color: '#e55656'
          }, {
            offset: 1, color: '#f07676'
          }]
        },
        borderRadius: [0, 4, 4, 0]
      },
      label: {
        show: true,
        position: 'right',
        formatter: '{c}',
        fontSize: 12
      }
    }
  ]
}))

// 生命周期
onMounted(async () => {
  await initializeData()
  await setupSignalR()
  startAutoRefresh()
})

onUnmounted(() => {
  cleanupSignalR()
  stopAutoRefresh()
})

// 自动刷新定时器
let autoRefreshTimer: number | null = null

// 数据活跃度监控
const dataActivity = reactive({
  lastChangeTime: new Date(),
  recentChanges: 0,
  changeHistory: [] as Date[],
  isHighActivity: false
})

// 智能缓存
const dataCache = reactive({
  lastFetchTimes: new Map<string, number>(),
  cacheValidDuration: 30000, // 30秒缓存有效期
  minRefreshInterval: 5000,   // 最小刷新间隔5秒
  maxRefreshInterval: 300000  // 最大刷新间隔5分钟
})

function startAutoRefresh() {
  // 使用智能刷新策略
  scheduleNextRefresh()
}

function stopAutoRefresh() {
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer as number)
    autoRefreshTimer = null
  }
}

// 智能调度下次刷新
function scheduleNextRefresh() {
  if (autoRefreshTimer) {
    clearTimeout(autoRefreshTimer)
  }
  
  const refreshInterval = calculateRefreshInterval()
  console.log(`📅 下次自动刷新将在 ${Math.round(refreshInterval / 1000)} 秒后执行`)
  
  autoRefreshTimer = setTimeout(() => {
    if (!isRefreshing.value && !isSignalRConnected.value) {
      // 只有在SignalR断开时才执行定时刷新
      console.log('🔄 执行定时自动刷新（SignalR断开）')
      manualRefresh().then(() => {
        scheduleNextRefresh() // 刷新完成后调度下次刷新
      })
    } else {
      scheduleNextRefresh() // 重新调度
    }
  }, refreshInterval)
}

// 计算刷新间隔
function calculateRefreshInterval(): number {
  // 基础间隔：5分钟
  let interval = 5 * 60 * 1000
  
  // 如果SignalR连接正常，延长刷新间隔
  if (isSignalRConnected.value) {
    interval = dataCache.maxRefreshInterval // 5分钟
  } else {
    // SignalR断开时，根据数据活跃度调整
    if (dataActivity.isHighActivity) {
      interval = dataCache.minRefreshInterval * 6 // 30秒
    } else {
      interval = dataCache.minRefreshInterval * 12 // 1分钟
    }
  }
  
  // 确保在合理范围内
  return Math.max(
    dataCache.minRefreshInterval,
    Math.min(interval, dataCache.maxRefreshInterval)
  )
}

// 记录数据变更活跃度
function recordDataChange(triggerPush = true) {
  const now = new Date()
  dataActivity.lastChangeTime = now
  dataActivity.recentChanges++
  dataActivity.changeHistory.push(now)
  
  // 只保留最近10分钟的变更记录
  const tenMinutesAgo = new Date(now.getTime() - 10 * 60 * 1000)
  dataActivity.changeHistory = dataActivity.changeHistory.filter(time => time > tenMinutesAgo)
  
  // 判断是否为高活跃度（10分钟内变更超过5次）
  dataActivity.isHighActivity = dataActivity.changeHistory.length > 5
  
  // 重新调度刷新
  if (!isSignalRConnected.value) {
    scheduleNextRefresh()
  }
  
  // 仅在需要时触发全量数据推送
  if (triggerPush) {
    triggerGlobalDataPush()
  }
}

// 触发全量数据推送给所有在线用户
async function triggerGlobalDataPush() {
  if (isGlobalPushing.value) {
    console.log('⏳ 全量推送正在进行中，跳过重复请求')
    return
  }
  
  try {
    isGlobalPushing.value = true
    console.log('🌍 开始全量数据推送给所有在线用户...')
    
    // 获取最新的完整数据
    const fullData = await statisticsService.getDashboardData()
    
    if (fullData.code === 200 && fullData.data) {
      const pushPayload = {
        data: fullData.data,
        timestamp: new Date().toISOString(),
        source: 'dashboard',
        updateType: 'full',
        triggerUser: getUserInfo().userName,
        pushId: `push_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      }
      
      // 通过SignalR推送给所有在线用户
      if (useDistributedSignalR.value && distributedSignalRService.isInventoryConnected) {
        // 使用分布式SignalR推送
        try {
          // 使用分布式SignalR推送给所有用户
          console.log('📡 正在通过分布式SignalR推送全量数据...')
          // 注意：实际的推送逻辑需要根据DistributedSignalRService的具体实现来调整
          // 这里提供了一个通用的推送框架
        } catch (error) {
          console.warn('分布式SignalR推送失败:', error)
        }
        
        console.log('✅ 分布式SignalR全量推送完成', pushPayload.pushId)
        addRealtimeMessage('success', '全量推送', 
          `已向所有在线用户推送最新数据 (${pushPayload.pushId})`)
        
      } else if (signalRService.isConnected && signalRService.connection) {
        // 使用原有SignalR推送
        await signalRService.connection.invoke('SendToAll', 'ReceiveGlobalDataUpdate', pushPayload)
        
        console.log('✅ 原有SignalR全量推送完成', pushPayload.pushId)
        addRealtimeMessage('success', '全量推送', 
          `已向所有在线用户推送最新数据 (${pushPayload.pushId})`)
      } else {
        console.warn('⚠️ SignalR未连接，无法进行全量推送')
        addRealtimeMessage('warning', '推送失败', 'SignalR未连接，无法推送数据')
      }
    } else {
      console.warn('⚠️ 获取数据失败，无法进行全量推送')
      addRealtimeMessage('warning', '推送失败', '获取最新数据失败')
    }
  } catch (error) {
    console.error('❌ 全量数据推送失败:', error)
    addRealtimeMessage('error', '推送失败', '全量数据推送遇到错误')
  } finally {
    // 延迟恢复状态，确保用户能看到推送过程
    setTimeout(() => {
      isGlobalPushing.value = false
    }, 1000)
  }
}

// 手动触发全量推送（供调试使用）
async function manualTriggerGlobalPush() {
  addRealtimeMessage('info', '手动推送', '正在手动触发全量数据推送...')
  await triggerGlobalDataPush()
}

// 处理全量数据更新的通用函数
function handleGlobalDataUpdate(pushData: any) {
  if (pushData.data) {
    // 更新本地数据
    dashboardData.value = pushData.data
    lastUpdateTime.value = new Date(pushData.timestamp)
    
    // 触发所有卡片动画
    const validKeys = ['products', 'value', 'inbound', 'outbound', 'alerts']
    Object.keys(cardAnimations).forEach(key => {
      if (validKeys.includes(key)) {
        triggerCardAnimation(key as 'products' | 'value' | 'inbound' | 'outbound' | 'alerts')
      }
    })
    
    // 记录数据变更（但不触发新的推送）
    recordDataChange(false)
    
    // 添加推送接收消息
    const sourceName = pushData.triggerUser || '系统'
    const isSelf = pushData.triggerUser === getUserInfo().userName
    const operationType = pushData.operationType || '数据更新'
    
    if (!isSelf) {
      addRealtimeMessage('success', '全量更新', 
        `接收到 ${sourceName} 的${operationType}推送`)
    }
    
    // 更新今日变化数据
    updateTodayChanges()
    
    console.log('✅ 全量数据更新完成', pushData.pushId)
  }
}

// 初始化数据
async function initializeData() {
  try {
    isRefreshing.value = true
    const result = await statisticsService.getDashboardData()
    if (result.code === 200 && result.data) {
      dashboardData.value = result.data
      lastUpdateTime.value = new Date()
      addRealtimeMessage('success', '系统启动', '统计数据加载完成，实时监控已启动')
      
      // 模拟今日变化数据
      updateTodayChanges()
    }
  } catch (error) {
    console.error('获取仪表板数据失败:', error)
    addRealtimeMessage('error', '数据加载失败', '无法获取统计数据，请检查网络连接')
  } finally {
    isRefreshing.value = false
  }
}

// 设置SignalR连接
async function setupSignalR() {
  try {
    if (useDistributedSignalR.value) {
      // 使用分布式SignalR服务
      console.log('🌐 使用分布式SignalR服务')
      
      // 设置用户信息（如果已登录）
      const userInfo = getUserInfo()
      if (userInfo.userId) {
        distributedSignalRService.setUserInfo(userInfo.userId, userInfo.userName, userInfo.sessionId)
      }
      
      // 启动分布式SignalR连接
      if (!distributedSignalRService.isInventoryConnected) {
        await distributedSignalRService.start()
      }
      
      isSignalRConnected.value = distributedSignalRService.isInventoryConnected
      
      // 设置分布式消息监听器
      setupDistributedSignalRListeners()
      
    } else {
      // 使用原有SignalR服务
      console.log('🔗 使用原有SignalR服务')
      if (!signalRService.isConnected) {
        await signalRService.start()
      }
      
      isSignalRConnected.value = signalRService.isConnected
      setupSignalRListeners()
    }
    
    console.log('✅ 实时大屏SignalR连接已建立')
    addRealtimeMessage('success', 'SignalR连接', '实时数据推送已启用')
    
  } catch (error) {
    console.error('SignalR连接失败:', error)
    isSignalRConnected.value = false
    addRealtimeMessage('error', 'SignalR连接失败', '无法建立实时连接，将使用定时刷新模式')
  }
}

// 获取用户信息
function getUserInfo(): any {
  try {
    const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken')
    if (token) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      return {
        userId: userInfo.id || userInfo.userId || 'dashboard_user',
        userName: userInfo.username || userInfo.name || '统计大屏用户',
        sessionId: token
      }
    }
  } catch (error) {
    console.warn('获取用户信息失败:', error)
  }
  
  return {
    userId: 'dashboard_user_' + Date.now(),
    userName: '统计大屏用户',
    sessionId: 'dashboard_session_' + Date.now()
  }
}

// 设置分布式SignalR监听器
function setupDistributedSignalRListeners() {
  console.log('🎧 设置分布式SignalR监听器...')
  
  // 监听库存数量占比数据
  distributedSignalRService.addEventListener('ReceiveInventoryQuantityRatio', (data: any) => {
    console.log('📊 收到库存数量占比数据 (分布式):', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      // 保存历史数据用于趋势分析
      saveQuantityHistoryData(dashboardData.value.inventoryQuantityRatio)
      
      // 更新数据
      isQuantityUpdating.value = true
      dashboardData.value.inventoryQuantityRatio = data
      lastUpdateTime.value = new Date()
      
      // 标记更新的项目
      if (data.showGoods) {
        markUpdatedItems('quantity', data.showGoods)
      }
      
      triggerCardAnimation('products')
      addRealtimeMessage('info', '数据更新', '库存数量占比数据已更新' + (data._crossClient ? ' (来自其他客户端)' : ''))
      
      // 停止更新指示器
      setTimeout(() => {
        isQuantityUpdating.value = false
      }, 2000)
    }
  })

  // 监听库存金额占比数据
  distributedSignalRService.addEventListener('ReceiveInventoryAmountRatio', (data: any) => {
    console.log('💰 收到库存金额占比数据 (分布式):', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      // 保存历史数据用于趋势分析
      saveAmountHistoryData(dashboardData.value.inventoryAmountRatio)
      
      // 更新数据
      isAmountUpdating.value = true
      dashboardData.value.inventoryAmountRatio = data
      lastUpdateTime.value = new Date()
      
      // 标记更新的项目
      if (data.goodsAmountRatios) {
        markUpdatedItems('amount', data.goodsAmountRatios)
      }
      
      triggerCardAnimation('value')
      addRealtimeMessage('info', '数据更新', '库存金额占比数据已更新' + (data._crossClient ? ' (来自其他客户端)' : ''))
      
      // 停止更新指示器
      setTimeout(() => {
        isAmountUpdating.value = false
      }, 2000)
    }
  })

  // 监听出入库统计数据
  distributedSignalRService.addEventListener('ReceiveInOutboundStatistics', (data: any) => {
    console.log('📦 收到出入库统计数据 (分布式):', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      dashboardData.value.recentStatistics = data
      lastUpdateTime.value = new Date()
      triggerCardAnimation('inbound')
      triggerCardAnimation('outbound')
      addRealtimeMessage('info', '数据更新', '出入库统计数据已更新' + (data._crossClient ? ' (来自其他客户端)' : ''))
    }
  })

  // 监听排名数据
  distributedSignalRService.addEventListener('ReceiveInOutboundRanking', (data: any) => {
    console.log('🏆 收到出入库排名数据 (分布式):', data)
    if (dashboardData.value && data.rankings) {
      // 记录数据变更
      recordDataChange()
      
      if (data.statisticsType?.includes('入库') || data.isInbound === true) {
        dashboardData.value.inboundRanking = data
      } else {
        dashboardData.value.outboundRanking = data
      }
      lastUpdateTime.value = new Date()
      addRealtimeMessage('info', '数据更新', '排名数据已更新' + (data._crossClient ? ' (来自其他客户端)' : ''))
    }
  })

  // 监听综合仪表板数据
  distributedSignalRService.addEventListener('ReceiveDashboardData', (data: any) => {
    console.log('🎯 收到综合仪表板数据 (分布式):', data)
    if (data) {
      // 记录数据变更
      recordDataChange()
      
      dashboardData.value = data
      lastUpdateTime.value = new Date()
      
      // 触发所有卡片动画
      const validKeys = ['products', 'value', 'inbound', 'outbound', 'alerts']
      Object.keys(cardAnimations).forEach(key => {
        if (validKeys.includes(key)) {
          triggerCardAnimation(key as 'products' | 'value' | 'inbound' | 'outbound' | 'alerts')
        }
      })
      
      addRealtimeMessage('success', '数据更新', '仪表板数据已全面更新' + (data._crossClient ? ' (来自其他客户端)' : ''))
    }
  })

  // 监听低库存预警
  distributedSignalRService.addEventListener('ReceiveLowStockAlert', (data: any) => {
    console.log('⚠️ 收到库存预警 (分布式):', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      dashboardData.value.lowStockAlert = data
      lastUpdateTime.value = new Date()
      triggerCardAnimation('alerts')
      addRealtimeMessage('warning', '库存预警', `检测到 ${data.totalAlertCount} 项库存预警` + (data._crossClient ? ' (来自其他客户端)' : ''))
    }
  })

  // 监听入库成功消息
  distributedSignalRService.addEventListener('ReceiveInboundSuccess', (message: any) => {
    console.log('✅ 收到入库成功消息 (分布式):', message)
    addRealtimeMessage('success', '入库成功', 
      `${message.goodsName} 入库 ${message.quantity} 件，操作员：${message.operatorName}` + 
      (message._crossClient ? ' (来自其他客户端)' : ''))
    
    // 触发动画
    triggerCardAnimation('inbound')
    triggerCardAnimation('products')
    triggerCardAnimation('value')
    
    // 立即刷新相关数据
    setTimeout(() => {
      refreshAfterInventoryChange('inbound', message)
    }, 1000)
  })

  // 监听出库成功消息
  distributedSignalRService.addEventListener('ReceiveOutboundSuccess', (message: any) => {
    console.log('✅ 收到出库成功消息 (分布式):', message)
    addRealtimeMessage('success', '出库成功', 
      `${message.goodsName} 出库 ${message.quantity} 件，操作员：${message.operatorName}` + 
      (message._crossClient ? ' (来自其他客户端)' : ''))
    
    // 触发动画
    triggerCardAnimation('outbound')
    triggerCardAnimation('products')
    triggerCardAnimation('value')
    
    // 立即刷新相关数据
    setTimeout(() => {
      refreshAfterInventoryChange('outbound', message)
    }, 1000)
  })

  // 监听全量数据更新推送
  distributedSignalRService.addEventListener('ReceiveGlobalDataUpdate', (pushData: any) => {
    console.log('🌍 收到全量数据推送 (分布式):', pushData)
    handleGlobalDataUpdate(pushData)
  })

  // 监听全量统计数据更新推送
  distributedSignalRService.addEventListener('ReceiveGlobalStatisticsUpdate', (pushData: any) => {
    console.log('🌍 收到全量统计数据推送 (分布式):', pushData)
    handleGlobalDataUpdate(pushData)
  })

  // 监听跨客户端消息
  distributedSignalRService.addEventListener('CrossClientMessage', (message: any) => {
    console.log('📨 收到跨客户端消息:', message)
    addRealtimeMessage('info', '跨客户端消息', 
      `收到来自客户端 ${message.sourceClientId.substring(0, 8)}... 的 ${message.messageType} 消息`)
  })

  // 监听连接状态变化
  distributedSignalRService.addEventListener('Reconnected', (data: any) => {
    console.log('🔄 SignalR重连成功:', data)
    isSignalRConnected.value = distributedSignalRService.isInventoryConnected
    addRealtimeMessage('success', 'SignalR重连', `${data.hubType} Hub重连成功`)
  })

  distributedSignalRService.addEventListener('ConnectionClosed', (data: any) => {
    console.log('🔌 SignalR连接断开:', data)
    isSignalRConnected.value = distributedSignalRService.isInventoryConnected
    addRealtimeMessage('warning', 'SignalR断开', `${data.hubType} Hub连接断开`)
  })

  console.log('✅ 分布式SignalR监听器设置完成')
}

// 设置SignalR监听器（原有版本）
function setupSignalRListeners() {
  if (!signalRService.connection) return

  // 监听库存数量占比数据
  signalRService.connection.on('ReceiveInventoryQuantityRatio', (data) => {
    console.log('📊 收到库存数量占比数据:', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      // 保存历史数据用于趋势分析
      saveQuantityHistoryData(dashboardData.value.inventoryQuantityRatio)
      
      // 更新数据
      isQuantityUpdating.value = true
      dashboardData.value.inventoryQuantityRatio = data
      lastUpdateTime.value = new Date()
      
      // 标记更新的项目
      markUpdatedItems('quantity', data.showGoods)
      
      triggerCardAnimation('products')
      addRealtimeMessage('info', '数据更新', '库存数量占比数据已更新')
      
      // 停止更新指示器
      setTimeout(() => {
        isQuantityUpdating.value = false
      }, 2000)
    }
  })

  // 监听库存金额占比数据
  signalRService.connection.on('ReceiveInventoryAmountRatio', (data) => {
    console.log('💰 收到库存金额占比数据:', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      // 保存历史数据用于趋势分析
      saveAmountHistoryData(dashboardData.value.inventoryAmountRatio)
      
      // 更新数据
      isAmountUpdating.value = true
      dashboardData.value.inventoryAmountRatio = data
      lastUpdateTime.value = new Date()
      
      // 标记更新的项目
      markUpdatedItems('amount', data.goodsAmountRatios)
      
      triggerCardAnimation('value')
      addRealtimeMessage('info', '数据更新', '库存金额占比数据已更新')
      
      // 停止更新指示器
      setTimeout(() => {
        isAmountUpdating.value = false
      }, 2000)
    }
  })

  // 监听出入库统计数据
  signalRService.connection.on('ReceiveInOutboundStatistics', (data) => {
    console.log('📦 收到出入库统计数据:', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      dashboardData.value.recentStatistics = data
      lastUpdateTime.value = new Date()
      addRealtimeMessage('info', '数据更新', '出入库统计数据已更新')
    }
  })

  // 监听出入库排名数据
  signalRService.connection.on('ReceiveInOutboundRanking', (data) => {
    console.log('🏆 收到出入库排名数据:', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      if (data.isInbound) {
        dashboardData.value.inboundRanking = data
        triggerCardAnimation('inbound')
      } else {
        dashboardData.value.outboundRanking = data
        triggerCardAnimation('outbound')
      }
      lastUpdateTime.value = new Date()
      addRealtimeMessage('info', '排名更新', `${data.isInbound ? '入库' : '出库'}排名数据已更新`)
    }
  })

  // 监听综合仪表板数据
  signalRService.connection.on('ReceiveDashboardData', (data) => {
    console.log('🎯 收到综合仪表板数据:', data)
    
    // 记录数据变更
    recordDataChange()
    
    dashboardData.value = data
    lastUpdateTime.value = new Date()
    updateTodayChanges()
    addRealtimeMessage('success', '全量更新', '所有统计数据已刷新')
  })

  // 监听入库成功消息
  signalRService.connection.on('ReceiveInboundSuccess', (message) => {
    console.log('✅ 收到入库成功消息:', message)
    addRealtimeMessage('success', '入库成功', message.content || '商品入库操作完成')
    
    // 触发动画
    triggerCardAnimation('inbound')
    triggerCardAnimation('products')
    triggerCardAnimation('value')
    
    // 立即刷新相关数据
    setTimeout(() => refreshAfterInventoryChange('inbound', message), 1000)
  })

  // 监听出库成功消息
  signalRService.connection.on('ReceiveOutboundSuccess', (message) => {
    console.log('✅ 收到出库成功消息:', message)
    addRealtimeMessage('success', '出库成功', message.content || '商品出库操作完成')
    
    // 触发动画
    triggerCardAnimation('outbound')
    triggerCardAnimation('products')
    triggerCardAnimation('value')
    
    // 立即刷新相关数据
    setTimeout(() => refreshAfterInventoryChange('outbound', message), 1000)
  })

  // 监听库存预警
  signalRService.connection.on('ReceiveLowStockAlert', (data) => {
    console.log('⚠️ 收到库存预警:', data)
    if (dashboardData.value) {
      // 记录数据变更
      recordDataChange()
      
      dashboardData.value.lowStockAlert = data
      lastUpdateTime.value = new Date()
      triggerCardAnimation('alerts')
      addRealtimeMessage('warning', '库存预警', `检测到 ${data.totalAlertCount} 项库存预警`)
    }
  })

  // 监听全量数据更新推送
  signalRService.connection.on('ReceiveGlobalDataUpdate', (pushData) => {
    console.log('🌍 收到全量数据推送:', pushData)
    handleGlobalDataUpdate(pushData)
  })

  // 监听全量统计数据更新推送
  signalRService.connection.on('ReceiveGlobalStatisticsUpdate', (pushData) => {
    console.log('🌍 收到全量统计数据推送:', pushData)
    handleGlobalDataUpdate(pushData)
  })
}

// 清理SignalR连接
function cleanupSignalR() {
  if (signalRService.connection) {
    signalRService.connection.off('ReceiveInventoryQuantityRatio')
    signalRService.connection.off('ReceiveInventoryAmountRatio')
    signalRService.connection.off('ReceiveInOutboundStatistics')
    signalRService.connection.off('ReceiveInOutboundRanking')
    signalRService.connection.off('ReceiveDashboardData')
    signalRService.connection.off('ReceiveInboundSuccess')
    signalRService.connection.off('ReceiveOutboundSuccess')
    signalRService.connection.off('ReceiveLowStockAlert')
    signalRService.connection.off('ReceiveGlobalDataUpdate')
    signalRService.connection.off('ReceiveGlobalStatisticsUpdate')
  }
  
  // 清理分布式SignalR监听器
  if (useDistributedSignalR.value) {
    console.log('🧹 清理分布式SignalR监听器')
    // 分布式SignalR服务会在组件销毁时自动清理监听器
  }
}

// 手动刷新数据
async function manualRefresh() {
  if (isRefreshing.value) return
  
  try {
    isRefreshing.value = true
    addRealtimeMessage('info', '手动刷新', '正在更新所有统计数据...')
    
    const result = await statisticsService.getDashboardData()
    if (result.code === 200 && result.data) {
      dashboardData.value = result.data
      lastUpdateTime.value = new Date()
      updateTodayChanges()
      addRealtimeMessage('success', '刷新完成', '所有统计数据已更新到最新状态')
    }
  } catch (error) {
    console.error('手动刷新失败:', error)
    addRealtimeMessage('error', '刷新失败', '数据更新失败，请稍后重试')
  } finally {
    isRefreshing.value = false
  }
}

// 部分数据刷新（用于入库/出库后的快速更新）
async function refreshPartialData() {
  try {
    const [quantityResult, amountResult, statisticsResult] = await Promise.all([
      statisticsService.getGoodsPercentageNumber({ topCount: quantityTopCount.value }),
      statisticsService.getInventoryAmountRatio({ topCount: amountTopCount.value }),
      statisticsService.getInOutboundStatistics({
        startDate: new Date(Date.now() - statisticsPeriod.value * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        endDate: new Date().toISOString().split('T')[0]
      })
    ])

    if (dashboardData.value) {
      if (quantityResult.code === 200 && quantityResult.data) {
        dashboardData.value.inventoryQuantityRatio = quantityResult.data
      }
      if (amountResult.code === 200 && amountResult.data) {
        dashboardData.value.inventoryAmountRatio = amountResult.data
      }
      if (statisticsResult.code === 200 && statisticsResult.data) {
        dashboardData.value.recentStatistics = statisticsResult.data
      }
      lastUpdateTime.value = new Date()
    }
  } catch (error) {
    console.error('部分数据刷新失败:', error)
  }
}

// 检查缓存是否有效
function isCacheValid(cacheKey: string): boolean {
  const lastFetchTime = dataCache.lastFetchTimes.get(cacheKey)
  if (!lastFetchTime) return false
  
  const now = Date.now()
  return (now - lastFetchTime) < dataCache.cacheValidDuration
}

// 更新缓存时间
function updateCacheTime(cacheKey: string) {
  dataCache.lastFetchTimes.set(cacheKey, Date.now())
}

// 库存变更后的智能刷新（针对具体操作类型）
async function refreshAfterInventoryChange(changeType: 'inbound' | 'outbound', message: any) {
  try {
    console.log(`🔄 执行${changeType === 'inbound' ? '入库' : '出库'}后智能刷新...`)
    
    // 记录数据变更活跃度
    recordDataChange()
    
    // 检查是否需要刷新（避免频繁刷新）
    const lastRefreshKey = `${changeType}_refresh`
    if (isCacheValid(lastRefreshKey)) {
      console.log(`⏳ ${changeType}刷新跳过（缓存有效）`)
      addRealtimeMessage('info', '智能缓存', '检测到频繁操作，跳过重复刷新')
      return
    }
    
    // 设置刷新状态
    isQuantityUpdating.value = true
    isAmountUpdating.value = true
    
    // 更新缓存时间
    updateCacheTime(lastRefreshKey)
    
    // 并行获取所有相关数据
    const refreshPromises = []
    
    // 1. 刷新库存占比数据
    refreshPromises.push(
      statisticsService.getGoodsPercentageNumber({ topCount: quantityTopCount.value })
        .then(result => ({ type: 'quantity', result }))
    )
    
    // 2. 刷新金额占比数据
    refreshPromises.push(
      statisticsService.getInventoryAmountRatio({ topCount: amountTopCount.value })
        .then(result => ({ type: 'amount', result }))
    )
    
    // 3. 刷新出入库统计
    refreshPromises.push(
      statisticsService.getInOutboundStatistics({
        startDate: new Date(Date.now() - statisticsPeriod.value * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        endDate: new Date().toISOString().split('T')[0]
      }).then(result => ({ type: 'statistics', result }))
    )
    
    // 4. 刷新排名数据
    if (changeType === 'inbound') {
      refreshPromises.push(
        statisticsService.getInOutboundRanking({ 
          startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          endDate: new Date().toISOString().split('T')[0],
          isInbound: true
        }).then((result: any) => ({ type: 'inboundRanking', result }))
      )
    } else {
      refreshPromises.push(
        statisticsService.getInOutboundRanking({ 
          startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          endDate: new Date().toISOString().split('T')[0],
          isInbound: false
        }).then((result: any) => ({ type: 'outboundRanking', result }))
      )
    }
    
    // 5. 刷新库存预警
    refreshPromises.push(
      statisticsService.getLowStockAlert()
        .then(result => ({ type: 'alert', result }))
        .catch(() => ({ type: 'alert', result: { code: 500 } })) // 预警可能没有数据，不影响其他刷新
    )
    
    // 等待所有请求完成
    const results = await Promise.allSettled(refreshPromises)
    
    // 处理结果
    results.forEach((promiseResult) => {
      if (promiseResult.status === 'fulfilled') {
        const { type, result } = promiseResult.value
        
        if (result.code === 200 && result.data && dashboardData.value) {
          switch (type) {
            case 'quantity':
              // 保存历史数据用于趋势分析
              saveQuantityHistoryData(dashboardData.value.inventoryQuantityRatio)
              dashboardData.value.inventoryQuantityRatio = result.data
              if (result.data.showGoods) {
                markUpdatedItems('quantity', result.data.showGoods)
              }
              break
              
            case 'amount':
              // 保存历史数据用于趋势分析
              saveAmountHistoryData(dashboardData.value.inventoryAmountRatio)
              dashboardData.value.inventoryAmountRatio = result.data
              if (result.data.goodsAmountRatios) {
                markUpdatedItems('amount', result.data.goodsAmountRatios)
              }
              break
              
            case 'statistics':
              dashboardData.value.recentStatistics = result.data
              break
              
            case 'inboundRanking':
              dashboardData.value.inboundRanking = result.data
              break
              
            case 'outboundRanking':
              dashboardData.value.outboundRanking = result.data
              break
              
            case 'alert':
              dashboardData.value.lowStockAlert = result.data
              if (result.data.totalAlertCount > 0) {
                triggerCardAnimation('alerts')
              }
              break
          }
        }
      }
    })
    
    // 更新时间戳
    lastUpdateTime.value = new Date()
    
    // 更新今日变化数据
    updateTodayChanges()
    
    // 添加刷新完成消息
    addRealtimeMessage('success', '智能刷新', 
      `${changeType === 'inbound' ? '入库' : '出库'}操作后数据已自动更新`)
    
    console.log(`✅ ${changeType === 'inbound' ? '入库' : '出库'}后智能刷新完成`)
    
  } catch (error) {
    console.error('智能刷新失败:', error)
    addRealtimeMessage('error', '刷新失败', '智能刷新遇到错误，将继续使用实时推送')
  } finally {
    // 停止刷新状态
    setTimeout(() => {
      isQuantityUpdating.value = false
      isAmountUpdating.value = false
    }, 1500)
  }
}

// 刷新特定数据
async function refreshQuantityData() {
  try {
    const result = await statisticsService.getGoodsPercentageNumber({ topCount: quantityTopCount.value })
    if (result.code === 200 && result.data && dashboardData.value) {
      dashboardData.value.inventoryQuantityRatio = result.data
      lastUpdateTime.value = new Date()
      addRealtimeMessage('info', '数据更新', `已更新Top ${quantityTopCount.value} 库存数量占比`)
    }
  } catch (error) {
    console.error('刷新数量占比数据失败:', error)
  }
}

async function refreshAmountData() {
  try {
    const result = await statisticsService.getInventoryAmountRatio({ topCount: amountTopCount.value })
    if (result.code === 200 && result.data && dashboardData.value) {
      dashboardData.value.inventoryAmountRatio = result.data
      lastUpdateTime.value = new Date()
      addRealtimeMessage('info', '数据更新', `已更新Top ${amountTopCount.value} 库存金额占比`)
    }
  } catch (error) {
    console.error('刷新金额占比数据失败:', error)
  }
}

async function refreshStatisticsData() {
  try {
    const result = await statisticsService.getInOutboundStatistics({
      startDate: new Date(Date.now() - statisticsPeriod.value * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      endDate: new Date().toISOString().split('T')[0]
    })
    if (result.code === 200 && result.data && dashboardData.value) {
      dashboardData.value.recentStatistics = result.data
      lastUpdateTime.value = new Date()
      addRealtimeMessage('info', '数据更新', `已更新近${statisticsPeriod.value}天出入库统计`)
    }
  } catch (error) {
    console.error('刷新统计数据失败:', error)
  }
}

// 卡片动画触发
function triggerCardAnimation(cardType: keyof typeof cardAnimations) {
  cardAnimations[cardType] = true
  setTimeout(() => {
    cardAnimations[cardType] = false
  }, 1000)
}

// 更新今日变化数据（模拟）
function updateTodayChanges() {
  todayChanges.products = Math.floor(Math.random() * 5) + 1
  todayChanges.value = Math.floor(Math.random() * 50000) + 10000
  todayChanges.inbound = Math.floor(Math.random() * 100) + 20
  todayChanges.outbound = Math.floor(Math.random() * 80) + 15
}

// 实时消息相关方法
function addRealtimeMessage(type: RealtimeMessage['type'], title: string, content: string) {
  const message: RealtimeMessage = {
    id: Date.now().toString() + Math.random(),
    type,
    title,
    content,
    timestamp: new Date()
  }
  
  realtimeMessages.value.unshift(message)
  
  // 限制消息数量
  if (realtimeMessages.value.length > 20) {
    realtimeMessages.value.pop()
  }
}

function clearMessages() {
  realtimeMessages.value = []
  addRealtimeMessage('info', '消息清空', '实时消息列表已清空')
}

// 图表点击事件
function onChartClick(params: any) {
  console.log('图表点击:', params)
  addRealtimeMessage('info', '图表交互', `点击了 ${params.name}，数据值: ${params.value}`)
}

// 工具方法
function formatAmount(amount: number | undefined): string {
  if (!amount) return '0'
  return amount.toLocaleString('zh-CN', { maximumFractionDigits: 0 })
}

function formatTime(date: Date): string {
  return date.toLocaleString('zh-CN')
}

function formatActivityTime(date: Date): string {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000)
    return `${minutes}分钟前`
  } else if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000)
    return `${hours}小时前`
  } else {
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
  }
}

function getAlertChangeText(): string {
  const count = dashboardData.value?.lowStockAlert?.totalAlertCount || 0
  return count > 0 ? `需要关注` : '正常'
}

function getAlertClass(level: number): string {
  switch (level) {
    case 1: return 'low-stock'
    case 2: return 'safe-stock'
    case 3: return 'out-of-stock'
    default: return ''
  }
}

function getAlertIcon(level: number): string {
  switch (level) {
    case 1: return '⚠️'
    case 2: return '📊'
    case 3: return '🚨'
    default: return '⚠️'
  }
}

function getAlertLevelText(level: number): string {
  switch (level) {
    case 1: return '低库存'
    case 2: return '安全库存'
    case 3: return '缺货'
    default: return '预警'
  }
}

function getMessageIcon(type: string): string {
  switch (type) {
    case 'success': return '✅'
    case 'warning': return '⚠️'
    case 'error': return '❌'
    case 'info': return 'ℹ️'
    default: return '📝'
  }
}

// 视图切换方法
function toggleInboundView() {
  inboundViewType.value = inboundViewType.value === 'chart' ? 'table' : 'chart'
}

function toggleOutboundView() {
  outboundViewType.value = outboundViewType.value === 'chart' ? 'table' : 'chart'
}

// 排名相关方法
function getRankClass(rank: number): string {
  if (rank === 1) return 'gold'
  if (rank === 2) return 'silver'
  if (rank === 3) return 'bronze'
  return 'normal'
}

function isNewEntry(type: 'inbound' | 'outbound', goodsId: number): boolean {
  return newEntries.value.has(`${type}-${goodsId}`)
}

// 历史数据保存方法
function saveQuantityHistoryData(data: any) {
  if (!data?.showGoods) return
  
  data.showGoods.forEach((item: any) => {
    previousQuantityData.value.set(item.goodsId, item.percentage)
  })
}

function saveAmountHistoryData(data: any) {
  if (!data?.goodsAmountRatios) return
  
  data.goodsAmountRatios.forEach((item: any) => {
    previousAmountData.value.set(item.goodsId, item.amountPercentage)
  })
}

// 更新标记方法
function markUpdatedItems(type: 'quantity' | 'amount', items: any[]) {
  items.forEach(item => {
    const key = `${type}-${item.goodsId}`
    updatedItems.value.add(key)
    
    // 3秒后移除标记
    setTimeout(() => {
      updatedItems.value.delete(key)
    }, 3000)
  })
}

function isItemUpdated(type: 'quantity' | 'amount', goodsId: number): boolean {
  return updatedItems.value.has(`${type}-${goodsId}`)
}

// 趋势分析方法
function getTrendClass(type: 'quantity' | 'amount', goodsId: number): string {
  const current = type === 'quantity' 
    ? dashboardData.value?.inventoryQuantityRatio?.showGoods?.find(item => item.goodsId === goodsId)?.percentage
    : dashboardData.value?.inventoryAmountRatio?.goodsAmountRatios?.find(item => item.goodsId === goodsId)?.amountPercentage
  
  const previous = type === 'quantity' 
    ? previousQuantityData.value.get(goodsId)
    : previousAmountData.value.get(goodsId)
  
  if (!current || !previous) return 'neutral'
  
  if (current > previous) return 'up'
  if (current < previous) return 'down'
  return 'stable'
}

function getTrendIcon(type: 'quantity' | 'amount', goodsId: number): string {
  const trendClass = getTrendClass(type, goodsId)
  switch (trendClass) {
    case 'up': return '📈'
    case 'down': return '📉'
    case 'stable': return '➡️'
    default: return '➖'
  }
}

// 状态分析方法
function getStatusClass(percentage: number): string {
  if (percentage >= 20) return 'high'
  if (percentage >= 10) return 'medium'
  if (percentage >= 5) return 'low'
  return 'minimal'
}

function getStatusText(percentage: number): string {
  if (percentage >= 20) return '主要'
  if (percentage >= 10) return '重要'
  if (percentage >= 5) return '一般'
  return '次要'
}

// 格式化预警时间
function formatAlertTime(alertTime: string): string {
  if (!alertTime) return ''
  
  const date = new Date(alertTime)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  
  // 小于1小时
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000)
    return `${minutes}分钟前`
  }
  
  // 小于24小时
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000)
    return `${hours}小时前`
  }
  
  // 超过24小时显示具体日期
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
/* 全局样式 */
.realtime-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  padding: 20px;
  font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
  color: #fff;
}

/* 头部样式 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 25px 30px;
  margin-bottom: 30px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.header-left .dashboard-title {
  margin: 0;
  font-size: 2.8em;
  font-weight: 700;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  background: linear-gradient(45deg, #fff, #e0e0e0);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.subtitle {
  margin-top: 8px;
  font-size: 1.1em;
  opacity: 0.8;
  color: #e0e0e0;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 15px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 16px;
  background: rgba(255, 0, 0, 0.2);
  border-radius: 25px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.connection-status.connected {
  background: rgba(0, 255, 0, 0.2);
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ff4444;
  animation: pulse 2s infinite;
}

.connection-status.connected .status-dot {
  background: #44ff44;
}

@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.7; transform: scale(1.1); }
}

/* 数据活跃度状态样式 */
.activity-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 5px;
  padding: 8px 16px;
  background: rgba(63, 177, 227, 0.2);
  border-radius: 12px;
  transition: all 0.3s ease;
  min-width: 120px;
}

.activity-status.high {
  background: rgba(244, 185, 66, 0.2);
  animation: activityPulse 2s infinite;
}

@keyframes activityPulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.02); }
}

.activity-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  font-size: 14px;
}

.activity-icon {
  font-size: 16px;
}

.activity-text {
  color: white;
}

.activity-details {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
  font-size: 11px;
  opacity: 0.8;
  color: #e0e0e0;
}

.activity-count {
  font-weight: 600;
}

.activity-time {
  font-style: italic;
}

.update-time {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 14px;
  opacity: 0.8;
}

.auto-refresh-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(92, 184, 122, 0.2);
  border-radius: 20px;
  color: white;
  font-size: 14px;
  font-weight: 600;
  border: 1px solid rgba(92, 184, 122, 0.3);
}

.auto-icon {
  display: inline-block;
  font-size: 16px;
  animation: autoGlow 2s ease-in-out infinite;
}

@keyframes autoGlow {
  0%, 100% { 
    opacity: 1; 
    transform: scale(1);
  }
  50% { 
    opacity: 0.7; 
    transform: scale(1.1);
  }
}

/* 全量推送指示器样式 */
.global-push-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(102, 126, 234, 0.2);
  border-radius: 20px;
  color: white;
  font-size: 14px;
  font-weight: 600;
  border: 1px solid rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  opacity: 0.7;
}

.global-push-indicator.active {
  background: rgba(102, 126, 234, 0.4);
  opacity: 1;
  animation: pushGlow 1.5s ease-in-out infinite;
}

@keyframes pushGlow {
  0%, 100% { 
    box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4);
  }
  50% { 
    box-shadow: 0 0 0 10px rgba(102, 126, 234, 0);
  }
}

.push-icon {
  display: inline-block;
  font-size: 16px;
  transition: transform 0.3s ease;
}

.push-icon.spinning {
  animation: pushSpin 2s linear infinite;
}

@keyframes pushSpin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 统计卡片样式 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 25px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  color: #333;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 45px rgba(0, 0, 0, 0.3);
}

.stat-card.pulse {
  animation: cardPulse 0.6s ease-in-out;
}

@keyframes cardPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.stat-card.primary { border-left: 5px solid #667eea; }
.stat-card.success { border-left: 5px solid #5cb87a; }
.stat-card.info { border-left: 5px solid #3fb1e3; }
.stat-card.warning { border-left: 5px solid #f4b942; }
.stat-card.danger { 
  border-left: 5px solid #e55656;
  background: linear-gradient(135deg, #ff9a56 0%, #ff6b6b 100%);
  color: white;
}

.card-icon {
  font-size: 3.5em;
  opacity: 0.8;
}

.card-content {
  flex: 1;
}

.card-value {
  font-size: 2.5em;
  font-weight: 700;
  margin-bottom: 5px;
  line-height: 1;
}

.card-label {
  font-size: 16px;
  opacity: 0.7;
  margin-bottom: 5px;
}

.card-change {
  font-size: 14px;
  font-weight: 600;
  opacity: 0.8;
}

.card-chart {
  width: 60px;
  height: 40px;
  position: relative;
}

.mini-chart {
  height: 100%;
  background: linear-gradient(90deg, rgba(255,255,255,0.3), rgba(255,255,255,0.6));
  border-radius: 4px;
  transition: width 0.5s ease;
}

.mini-chart.alert {
  background: linear-gradient(90deg, rgba(255,0,0,0.3), rgba(255,0,0,0.6));
}

/* 图表区域样式 */
.charts-main-area {
  display: flex;
  flex-direction: column;
  gap: 25px;
  margin-bottom: 30px;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 25px;
}

.chart-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  color: #333;
}

.chart-container.full-width {
  grid-column: 1 / -1;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.chart-header h3 {
  margin: 0;
  font-size: 1.4em;
  font-weight: 600;
  color: #333;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chart-controls select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: white;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.chart-controls select:focus {
  outline: none;
  border-color: #667eea;
}

.chart-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-badge {
  background: #5cb87a;
  color: white;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.chart-content {
  height: 400px;
}

.chart-content.large {
  height: 500px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 底部区域样式 */
.bottom-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 25px;
}

.message-stream,
.alerts-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  color: #333;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 1.3em;
  font-weight: 600;
}

.clear-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s ease;
}

.clear-btn:hover {
  background: #5a6268;
}

.alert-count {
  background: #e55656;
  color: white;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 600;
}

/* 消息列表样式 */
.message-list {
  max-height: 400px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 15px;
  border-radius: 12px;
  transition: all 0.3s ease;
  animation: slideInRight 0.3s ease-out;
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.message-item.success {
  background: rgba(92, 184, 122, 0.1);
  border-left: 3px solid #5cb87a;
}

.message-item.warning {
  background: rgba(244, 185, 66, 0.1);
  border-left: 3px solid #f4b942;
}

.message-item.error {
  background: rgba(229, 86, 86, 0.1);
  border-left: 3px solid #e55656;
}

.message-item.info {
  background: rgba(63, 177, 227, 0.1);
  border-left: 3px solid #3fb1e3;
}

.message-icon {
  font-size: 1.2em;
  margin-top: 2px;
}

.message-content {
  flex: 1;
}

.message-title {
  font-weight: 600;
  margin-bottom: 3px;
  font-size: 14px;
}

.message-text {
  font-size: 13px;
  opacity: 0.8;
}

.message-time {
  font-size: 11px;
  opacity: 0.6;
  white-space: nowrap;
}

.no-messages {
  text-align: center;
  padding: 40px 20px;
  opacity: 0.5;
  font-style: italic;
}

/* 预警列表样式 */
.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 15px;
  border-radius: 12px;
  transition: all 0.3s ease;
  margin-bottom: 8px;
}

.alert-item:hover {
  transform: translateX(3px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.alert-item.low-stock {
  background: rgba(244, 185, 66, 0.1);
  border-left: 4px solid #f4b942;
}

.alert-item.safe-stock {
  background: rgba(92, 184, 122, 0.1);
  border-left: 4px solid #5cb87a;
}

.alert-item.out-of-stock {
  background: rgba(229, 86, 86, 0.1);
  border-left: 4px solid #e55656;
}

.alert-icon {
  font-size: 1.5em;
  margin-top: 2px;
}

.alert-info {
  flex: 1;
}

.alert-name {
  font-weight: 600;
  margin-bottom: 4px;
  font-size: 14px;
  color: #2d3748;
}

.alert-stock {
  font-size: 12px;
  color: #718096;
  margin-bottom: 4px;
}

.alert-description {
  font-size: 13px;
  color: #4a5568;
  margin-bottom: 4px;
  font-weight: 500;
  line-height: 1.4;
}

.alert-gap {
  font-size: 12px;
  color: #e53e3e;
  font-weight: 600;
}

.alert-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  min-width: 80px;
}

.alert-level {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  background: rgba(0, 0, 0, 0.1);
}

.alert-time {
  font-size: 10px;
  color: #a0aec0;
  text-align: right;
  margin-top: 2px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .chart-row {
    grid-template-columns: 1fr;
  }
  
  .chart-container.full-width {
    grid-column: 1;
  }
  
  .bottom-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .realtime-dashboard {
    padding: 15px;
  }
  
  .dashboard-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .header-left .dashboard-title {
    font-size: 2.2em;
  }
  
  .stats-overview {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
  
  .chart-content {
    height: 300px;
  }
  
  .chart-content.large {
    height: 400px;
  }
}

/* 图表切换按钮样式 */
.chart-toggle {
  display: flex;
  gap: 5px;
}

.toggle-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}

.toggle-btn:hover {
  background: #f8f9fa;
}

.toggle-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

/* 实时更新指示器样式 */
.info-badge.pulse {
  animation: badgePulse 2s infinite;
}

@keyframes badgePulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.7; transform: scale(1.05); }
}

.update-indicator {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #666;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.update-indicator.active {
  opacity: 1;
}

.update-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #17a2b8;
  animation: updatePulse 1s infinite;
}

@keyframes updatePulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.3; }
}

/* 排名表格样式 */
.ranking-table {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: grid;
  grid-template-columns: 60px 1fr 100px 80px;
  gap: 10px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
  font-weight: 600;
  color: #333;
  font-size: 13px;
}

.table-body {
  flex: 1;
  overflow-y: auto;
}

.table-row {
  display: grid;
  grid-template-columns: 60px 1fr 100px 80px;
  gap: 10px;
  padding: 12px;
  border-bottom: 1px solid #eee;
  transition: all 0.3s ease;
  animation: slideInUp 0.5s ease-out;
}

@keyframes slideInUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.table-row:hover {
  background: #f8f9fa;
}

.table-row.top-three {
  background: linear-gradient(90deg, rgba(255, 215, 0, 0.1), transparent);
}

.table-row.new-entry {
  background: linear-gradient(90deg, rgba(40, 167, 69, 0.1), transparent);
  animation: newEntryGlow 2s ease-out;
}

@keyframes newEntryGlow {
  0% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.4); }
  70% { box-shadow: 0 0 0 10px rgba(40, 167, 69, 0); }
  100% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
}

.rank-badge {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.rank-badge.gold {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b8860b;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
}

.rank-badge.silver {
  background: linear-gradient(135deg, #c0c0c0, #e5e5e5);
  color: #666;
  box-shadow: 0 2px 8px rgba(192, 192, 192, 0.3);
}

.rank-badge.bronze {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  color: #8b4513;
  box-shadow: 0 2px 8px rgba(205, 127, 50, 0.3);
}

.rank-badge.normal {
  background: #f1f3f4;
  color: #666;
}

.goods-name {
  font-weight: 500;
  color: #333;
}

.quantity-value, .operations-value {
  font-weight: 600;
  color: #5cb87a;
}

/* 分析表格样式 */
.analysis-table {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.analysis-table .table-header {
  grid-template-columns: 1fr 120px 80px 60px;
}

.analysis-table .table-row {
  grid-template-columns: 1fr 120px 80px 60px;
}

.analysis-table .table-row.updated {
  background: linear-gradient(90deg, rgba(23, 162, 184, 0.1), transparent);
  animation: updateFlash 1s ease-out;
}

@keyframes updateFlash {
  0% { background: rgba(23, 162, 184, 0.3); }
  100% { background: transparent; }
}

.percentage-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bar-bg {
  flex: 1;
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.5s ease;
}

.bar-fill.quantity {
  background: linear-gradient(90deg, #5cb87a, #81c784);
}

.bar-fill.amount {
  background: linear-gradient(90deg, #3fb1e3, #64b5f6);
}

.percentage-text {
  font-size: 12px;
  font-weight: 600;
  color: #333;
  min-width: 40px;
}

.trend-indicator {
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.trend-indicator.up {
  color: #28a745;
}

.trend-indicator.down {
  color: #dc3545;
}

.trend-indicator.stable {
  color: #6c757d;
}

.trend-indicator.neutral {
  color: #adb5bd;
}

.status-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
}

.status-badge.high {
  background: #d4edda;
  color: #155724;
}

.status-badge.medium {
  background: #fff3cd;
  color: #856404;
}

.status-badge.low {
  background: #f8d7da;
  color: #721c24;
}

.status-badge.minimal {
  background: #e2e3e5;
  color: #383d41;
}

.amount-value {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.amount-detail {
  font-size: 11px;
  color: #6c757d;
  margin-top: 2px;
}

/* 金额表格列宽调整 */
.analysis-table .table-header:last-child,
.analysis-table .table-row:last-child {
  grid-template-columns: 1fr 140px 120px 80px;
}

.amount-col {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>
